package com.myk.game.lib;

import java.util.HashMap;
import java.util.Map;

/**
 * 交复往返任务策略中心
 */
public class RotaryReverseCenter {

    private Map<String, RotaryReverseBean> rotaryReverseBeanMap;

    /**
     * 每个RotaryReverseCenter都是一个交复往返集合
     */
    public RotaryReverseCenter() {
        rotaryReverseBeanMap = new HashMap<>();
    }

    /**
     * 注册一组交复往返的事件
     */
    public void register(String key, boolean isPositive, Runnable positiveAction, Runnable negationAction) {
        RotaryReverseBean bean = new RotaryReverseBean(isPositive, positiveAction, negationAction);
        rotaryReverseBeanMap.put(key, bean);
    }

    /**
     * 取消注册
     */
    public void unRegister(String key) {
        rotaryReverseBeanMap.remove(key);
    }

    /**
     * 返回该key的状态是什么，true:Positive状态  ， false:Negative状态
     */
    public boolean getIsPositiveByKey(String key) {
        return rotaryReverseBeanMap.get(key).isPos;
    }

    /**
     * 通知该key切换为正向,其余皆为反向
     */
    public void noticeFocusPositive(String key) {
        for (Map.Entry<String, RotaryReverseBean> beanEntry : rotaryReverseBeanMap.entrySet()) {
            if (beanEntry.getKey().equals(key)) {
                beanEntry.getValue().changePositive();
            }
            else {
                beanEntry.getValue().changeNegative();
            }
        }
    }

    /**
     * 通知这组策略所有集合都切换为某一状态
     */
    public void noticeAllChangeTo(boolean isPositive) {
        if (isPositive) {
            for (Map.Entry<String, RotaryReverseBean> beanEntry : rotaryReverseBeanMap.entrySet()) {
                beanEntry.getValue().changePositive();
            }
        }
        else {
            for (Map.Entry<String, RotaryReverseBean> beanEntry : rotaryReverseBeanMap.entrySet()) {
                beanEntry.getValue().changeNegative();
            }
        }
    }

    /**
     * 下面这些api以后有必要的时候再去实现
     */
    /*public void noticeFocusTo(String key,boolean isPositive){

    }

    public void noticeFocusChange(String key){

    }

    public void noticeFocusNegative(String key){

    }

    public void noticeAllChange(){

    }*/

    //交复往返策略实体
    private static class RotaryReverseBean {

        private boolean isPos; //true正面状态，false反面状态
        private Runnable posAction; //正向动作
        private Runnable negAction; //反向动作

        protected RotaryReverseBean(boolean isPos, Runnable pos, Runnable neg) {
            this.isPos = isPos;
            this.posAction = pos;
            this.negAction = neg;
        }

        //切换为正向，如果本身是反向就会执行正向动作
        protected void changePositive() {
            if (!isPos) {
                isPos = true;
                posAction.run();
            }
        }

        //切换为反向，如果本身是正向就会执行反向动作
        protected void changeNegative() {
            if (isPos) {
                isPos = false;
                negAction.run();
            }
        }

    }
}
